<script>
import User from '@/components/Check/User'

import { atLeast, atLeastN, value } from '@/utils/kris_utils'
export default {
  components: {
    User
  },
  props: {
    isEditing: {
      type: Boolean,
      required: true,
      default: false
    },
    value: {
      required: true,
      default() {
        return null
      }
    },
    fallback: {
      type: String,
      default: '-'
    }
  },
  data() {
    return {
      dialogVisible: false,
      current: null
    }
  },
  computed: {
    leaderFormatted() {
      if (!atLeast(this.value, ['label', 'value'])) { return this.fallback }

      return this.value.label
    }
  },
  methods: {
    handleClose() {
      this.dialogVisible = false
    },
    closeDialog() {
      this.dialogVisible = false
    },
    confirm() {
      this.$emit('input', this.current)
      this.closeDialog()
    },
    handleChange(e) {
      if (!atLeastN(e, 1)) { return }

      if (!atLeast(e[0], ['id', 'username'])) { return }

      this.current = { label: e[0].username, value: e[0].id }
    }
  }
}
</script>

<template>
  <div>
    <span>{{ leaderFormatted }}</span>
        &nbsp;

    <el-button
      v-if="isEditing"
      type="text"
      @click="dialogVisible = true"
    >
      <i class="el-icon-edit-outline" />
      更换
    </el-button>

    <el-dialog
      title="领导修改"
      width="40%"
      :before-close="handleClose"
      :visible.sync="dialogVisible"
    >
      <User v-if="dialogVisible" @change="handleChange" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
